﻿
using SuperSocialShare.Authorize;
using SuperSocialShare.Error;
using SuperSocialShare.Helper;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
namespace SuperSocialShare.Clients
{
    public class TencentClient : SocialClient
    {
        protected override string GetAccessTokenUrl
        {
            get { return "https://open.t.qq.com/cgi-bin/oauth2/access_token"; }
        }

        protected override string AuthorizeUrl
        {
            get { return "https://open.t.qq.com/cgi-bin/oauth2/authorize"; }
        }

        protected override string GetUserInfoUrl
        {
            get { return "https://open.t.qq.com/api/user/info"; }
        }

        protected override string UpdateStatusUrl
        {
            get { return "https://open.t.qq.com/api/t/add"; }
        }

        protected override string UploadImageUrl
        {
            get { return "https://open.t.qq.com/api/t/add_pic"; }
        }

        protected override string RevokeAuthorizeUrl
        {
            get { throw new NotImplementedException(); }
        }

        public override SocialType SocialType
        {
            get { return SocialType.Tencent; }
        }

        internal override string GetRequestAuthorizeUrl()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>() 
            {
                {"client_id",ClientId},
                {"response_type","code"},
                {"redirect_uri",CallbackUrl},
                {"wap","2"}
            };
            return Utility.BuildQueryString(AuthorizeUrl, parameters);
        }

        internal override void ProcessResponseDataOfAuthorize(string data)
        {
            // string requestAccessTokenUrl = "";
            string code = Utility.GetRegexContent(@"(?<=code=)[^&]*", data);
            TencentAuthorizeInfo authorizeInfo = new TencentAuthorizeInfo();
            authorizeInfo.ClientId = ClientId;
            authorizeInfo.OpenID = Utility.GetRegexContent(@"(?<=openid=)[^&]*", data);
            authorizeInfo.OpenKey = Utility.GetRegexContent(@"(?<=openkey=)[^&]*", data);

            AuthorizeManager.Save(authorizeInfo, SocialType);//保存带有openid和openkey的授权信息

            HttpWebRequester requester = new HttpWebRequester();
            requester.Parameters.Add(new RequestParameter("code", code));
            requester.Parameters.Add(new RequestParameter("client_id", ClientId));
            requester.Parameters.Add(new RequestParameter("client_secret", ClientSecret));
            requester.Parameters.Add(new RequestParameter("redirect_uri", CallbackUrl));
            requester.Parameters.Add(new RequestParameter("grant_type", "authorization_code"));
            requester.RequestCompleted += requester_RequestCompleted;
            requester.BeginRequest(GetAccessTokenUrl, 0);
        }

        protected override void GetUserInfoAsync(AuthorizeInfo info)
        {
            TencentAuthorizeInfo authorizeInfo = info as TencentAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.Parameters.Add(new RequestParameter("format", "json"));
                requester.Parameters.Add(new RequestParameter("oauth_consumer_key", ClientId));
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.Parameters.Add(new RequestParameter("openid", authorizeInfo.OpenID));
                requester.Parameters.Add(new RequestParameter("oauth_version", "2.a"));
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(GetUserInfoUrl, 3);
            }
        }

        public override void RevokeAuthorizeAysnc()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 分享文字
        /// </summary>
        public override void ShareText(string content)
        {
            TencentAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as TencentAuthorizeInfo;
            if (authorizeInfo != null)
            {
                //string url = ;
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
                requester.Parameters.Add(new RequestParameter("format", "json"));
                requester.Parameters.Add(new RequestParameter("content", content));
                requester.Parameters.Add(new RequestParameter("clientip", string.Empty));
                requester.Parameters.Add(new RequestParameter("oauth_consumer_key", authorizeInfo.ClientId));
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.Parameters.Add(new RequestParameter("openid", authorizeInfo.OpenID));
                requester.Parameters.Add(new RequestParameter("oauth_version", "2.a"));
                requester.Parameters.Add(new RequestParameter("scope", "all"));
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UpdateStatusUrl, 1, "POST");
            }
        }

        public override void ShareTextWithImage(string content, byte[] imgdata)
        {
            TencentAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as TencentAuthorizeInfo;
            if (authorizeInfo != null)
            {
                //string url = ;
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.MULTIPART_FORM_DATA;
                requester.Parameters.Add(new RequestParameter("oauth_consumer_key", authorizeInfo.ClientId));
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.Parameters.Add(new RequestParameter("openid", authorizeInfo.OpenID));
                requester.Parameters.Add(new RequestParameter("oauth_version", "2.a"));
                requester.Parameters.Add(new RequestParameter("scope", "all"));
                requester.Parameters.Add(new RequestParameter("format", "json"));
                requester.Parameters.Add(new RequestParameter("content", content));
                requester.Parameters.Add(new RequestParameter("pic", imgdata));
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UploadImageUrl, 1, "POST");
            }
        }

        void requester_RequestCompleted(RequestCompletedEventArgs e)
        {
            AsyncEventArgs args = new AsyncEventArgs();
            int actionTag = Convert.ToInt32(e.UserData);
            if (e.Error == null)
            {
                TencentError error = JsonConverter.GetObjectFromJsonString<TencentError>(e.Result);
                if (error != null && error.ErrorCode != 0)
                    args.Error = error;
                if (actionTag == 0)//返回数据为授权信息
                {
                    TencentAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as TencentAuthorizeInfo;
                    if (authorizeInfo != null)
                    {
                        UserInfo userInfo = new UserInfo();
                        userInfo.Fill(e.Result, SocialType);
                        authorizeInfo.UserInfo = userInfo;
                        authorizeInfo.AccessToken = Utility.GetRegexContent(@"(?<=access_token=)[^&]*", e.Result);
                        authorizeInfo.Expires = Convert.ToInt32(Utility.GetRegexContent(@"(?<=expires_in=)[^&]*", e.Result));
                        authorizeInfo.UserInfo = new UserInfo()
                        {
                            UserName = Utility.GetRegexContent(@"(?<=nick=)[^&]*", e.Result)
                        };
                        args.Result = authorizeInfo;
                    }
                    OnGetAuthorizeInfoCompleted(args);
                }
                else //获取的数据为分享后的返回数据
                {
                    OnShareCompleted(args);
                }
            }
            else//WebException 
            {
                args.Error = new Error.ErrorBase(e.Error);
                if (actionTag == 0)
                {
                    OnGetAuthorizeInfoCompleted(args);
                }
                else
                {
                    OnShareCompleted(args);
                }
            }
        }
    }
}
